import { Button, Drawer, message } from 'antd';
import { ColForm, ColFormItem } from 'components/UILibrary/colForm';
import { checkPermission } from 'permission/Index';
import React from 'react';
import { JSONObject } from 'admin/schema/common';
import { PermissionType } from 'admin/schema/PermissionTypes';

interface OperationProp {
  formConfig: ColFormItem[];
  btnCaption: string;
  permissionType: PermissionType;
  fetchListApi: () => Promise<any>;
  submitApi: (params: JSONObject[]) => Promise<any>;
  callback: () => void;
}

interface OperationState {
  visible: boolean;
}

export class MonitorOperationDrawer extends React.Component<OperationProp, OperationState> {
  private colFormRef: React.RefObject<ColForm>;

  constructor(prop: OperationProp) {
    super(prop);
    this.colFormRef = React.createRef();
    this.state = {
      visible: false,
    };
  }

  public show(): void {
    this.setState(
      {
        visible: true,
      },
      () => {
        this.props
          .fetchListApi()
          .then(res => {
            this.colFormRef.current?.setValue(res);
          })
          .catch(error => {
            console.error(`系统异常: ${JSON.stringify(error)}`);
          });
      }
    );
  }

  public close(): void {
    this.setState({
      visible: false,
    });
  }

  private submitData(): void {
    const api = this.props.submitApi;
    let value = this.colFormRef.current?.getValue();
    // 去除参数不完整的项
    const keys = this.props.formConfig.map(son => son.key);
    value = value?.filter(rowItem => {
      let passNull = true;
      keys.forEach(key => {
        if (!rowItem[key]) {
          passNull = false;
        }
      });
      return passNull;
    });
    // 验证指标名是否重复
    const itemNames = value?.map(item => {
      return item.fsName || item.scName;
    });
    if (itemNames?.length !== Array.from(new Set(itemNames)).length) {
      message.warn('指标名重复');
      return;
    }
    api(value as JSONObject[]).then(() => {
      message.success('提交成功');
      this.props.callback();
      this.close();
    });
  }

  /**
   * 渲染抽屉底部footer
   */
  private buildFooter(): JSX.Element {
    return (
      <div className="drawer-footer-buttongroup">
        {checkPermission(this.props.permissionType) && (
          <Button
            type="primary"
            onClick={() => {
              this.submitData();
            }}
          >
            确定
          </Button>
        )}
        <Button onClick={this.close.bind(this)}>取消</Button>
      </div>
    );
  }

  render() {
    const { visible } = this.state;
    const { colFormRef } = this;

    return (
      <Drawer
        className="monitor-operation-drawer"
        width={500}
        visible={visible}
        title="配置"
        onClose={this.close.bind(this)}
        footer={this.buildFooter()}
      >
        <ColForm ref={colFormRef} col={this.props.formConfig} btnCaption={this.props.btnCaption} />
      </Drawer>
    );
  }
}
